package com.buaa.divinationmaster;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.textfield.TextInputEditText;
import com.buaa.divinationmaster.adapter.HistoryAdapter;
import com.buaa.divinationmaster.manager.DatabaseManager;
import com.buaa.divinationmaster.model.DivinationRecord;

import java.util.ArrayList;
import java.util.List;

/**
 * 历史记录页面
 * 根据需求文档实现历史记录查看、搜索、筛选功能
 */
public class HistoryActivity extends AppCompatActivity {
    
    private TextInputEditText etSearch;
    private RecyclerView rvHistory;
    private LinearLayout layoutEmptyState;
    private HistoryAdapter adapter;
    private List<DivinationRecord> allRecords;
    private DatabaseManager databaseManager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        
        setupToolbar();
        initViews();
        loadHistoryData();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("历史记录");
        }
    }
    
    private void initViews() {
        etSearch = findViewById(R.id.etSearch);
        rvHistory = findViewById(R.id.rvHistory);
        layoutEmptyState = findViewById(R.id.layoutEmptyState);
        
        databaseManager = DatabaseManager.getInstance(this);
        allRecords = new ArrayList<>();
        
        // 设置RecyclerView
        rvHistory.setLayoutManager(new LinearLayoutManager(this));
        adapter = new HistoryAdapter(this, allRecords);
        rvHistory.setAdapter(adapter);
        
        // 设置搜索功能
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filterRecords(s.toString());
            }
            
            @Override
            public void afterTextChanged(Editable s) {}
        });
    }
    
    private void loadHistoryData() {
        databaseManager.getAllRecords(new DatabaseManager.OnDataCallback<List<DivinationRecord>>() {
            @Override
            public void onSuccess(List<DivinationRecord> records) {
                runOnUiThread(() -> {
                    allRecords.clear();
                    allRecords.addAll(records);
                    adapter.notifyDataSetChanged();
                    
                    // 显示/隐藏空状态
                    if (records.isEmpty()) {
                        rvHistory.setVisibility(View.GONE);
                        layoutEmptyState.setVisibility(View.VISIBLE);
                    } else {
                        rvHistory.setVisibility(View.VISIBLE);
                        layoutEmptyState.setVisibility(View.GONE);
                    }
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(() -> {
                    Toast.makeText(HistoryActivity.this, "加载历史记录失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                    rvHistory.setVisibility(View.GONE);
                    layoutEmptyState.setVisibility(View.VISIBLE);
                });
            }
        });
    }
    
    private void filterRecords(String keyword) {
        if (keyword.trim().isEmpty()) {
            adapter.updateRecords(allRecords);
        } else {
            databaseManager.searchRecords(keyword, new DatabaseManager.OnDataCallback<List<DivinationRecord>>() {
                @Override
                public void onSuccess(List<DivinationRecord> records) {
                    runOnUiThread(() -> {
                        adapter.updateRecords(records);
                    });
                }
                
                @Override
                public void onError(Exception error) {
                    runOnUiThread(() -> {
                        Toast.makeText(HistoryActivity.this, "搜索失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            });
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
